import React, { ReactElement, useRef, useEffect } from 'react'
import { Modal, Form, FormInstance, Input, TreeSelect, message } from 'antd'
import { DepartmentSchema } from '@src/components/schema/departmentSchema'
import { addDepartmentRequest, updateDepartmentRequest } from './ajax'
import { awaitWrap } from '@src/assets/js/tool'
import { TreeData } from '@src/components/schema/tree'

const { Item } = Form

interface Props {
  visible: boolean
  hide: () => void
  tenantCode: string
  data: DepartmentSchema | null
  treeData: TreeData[]
  refreshData: () => void
}

interface FormData {
  id?: string
  pid: string
  name: string
  sname: string
  type: string
}

async function submitHandle (d: FormData, tenantCode: string, refreshData: () => void, hide: () => void): Promise<void> {
  let e: Error | null = null
  const h = message.loading('提交中', 120)
  if (d.id === undefined) {
    const r = await awaitWrap(addDepartmentRequest(tenantCode, d.pid, d.name, d.sname))
    e = r[0]
  } else {
    const r = await awaitWrap(updateDepartmentRequest(d.id, tenantCode, d.pid, d.name, d.sname))
    e = r[0]
  }
  h()
  if (e === null) {
    message.success(d.id === undefined ? '添加成功' : '更新成功').then(null, null)
    refreshData()
    hide()
  }
}

function Main ({ visible, hide, data, treeData, tenantCode, refreshData }: Props): ReactElement {
  const ref = useRef<FormInstance>(null)
  useEffect(() => {
    if (visible) {
      if (data === null) {
        ref.current?.resetFields()
      } else {
        ref.current?.setFieldsValue(data)
      }
    }
  }, [visible])
  return (
    <Modal title={data !== null ? '编辑部门' : '新增部门'} visible={visible} onOk={() => ref.current?.submit()} maskClosable={false} onCancel={() => hide()}>
      <Form ref={ref} onFinish={async d => await submitHandle(d, tenantCode, refreshData, hide)}>
        <Item name='id' noStyle><span /></Item>
        <Item label='上级部门' name='pid' rules={[{ required: true, message: '部门名称不能为空' }]}>
          <TreeSelect
            style={{ width: '100%' }}
            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
            treeData={treeData}
            placeholder="请选择"
            treeDefaultExpandAll
          />
        </Item>
        <Item label='部门名称' name='name' rules={[{ required: true, message: '部门名称不能为空' }]}>
          <Input placeholder='请输入' />
        </Item>
        <Item label='部门简称' name='sname' rules={[{ required: true, message: '部门简称不能为空' }]}>
          <Input placeholder='请输入' />
        </Item>
      </Form>
    </Modal>
  )
}

export default Main
